package com.example.itcacp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.itcacp.entity.BrowseHistory;
import com.example.itcacp.repository.mybatis.BrowseHistoryMapper;
import com.example.itcacp.service.BrowseHistoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BrowseHistoryServiceImpl extends ServiceImpl<BrowseHistoryMapper, BrowseHistory> implements BrowseHistoryService {

    @Resource
    private BrowseHistoryMapper browseHistoryMapper;

    /**
     * 添加浏览记录
     * */
    @Override
    public void addBrowseHistory(BrowseHistory browseHistory) {
        browseHistoryMapper.insert ( browseHistory );
    }


    @Override
    public PageInfo<BrowseHistory> getBrowseHistoryByTimeRange(Integer pageNum, Integer pageSize, Long userId, TimeRange timeRange) {
        PageHelper.startPage ( pageNum, pageSize );
        LambdaQueryWrapper<BrowseHistory> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(BrowseHistory::getUserId, userId);
        // 根据时间范围设置查询条件
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;
        switch (timeRange) {
            case TODAY:
                startTime = LocalDate.now ().atStartOfDay();
                break;
            case YESTERDAY:
                startTime = LocalDate.now().minusDays(1).atStartOfDay();
                endTime = LocalDate.now().atStartOfDay();
                break;
            case THIS_WEEK:
                startTime = LocalDate.now().minusDays(7).atStartOfDay();
                break;
            case THIS_MONTH:
                startTime = LocalDate.now().minusMonths(1).atStartOfDay();
                break;
            case THREE_MONTHS:
                startTime = LocalDate.now().minusMonths(3).atStartOfDay();
                break;
            case EARLIER:
                endTime = LocalDate.now().minusMonths(3).atStartOfDay();
                break;
        }
        if (startTime != null) {
            wrapper.ge(BrowseHistory::getCreated_at, startTime);
        }
        if (endTime != null) {
            wrapper.lt(BrowseHistory::getCreated_at, endTime);
        }
        // 按浏览时间倒序排列
//        wrapper.orderByDesc(BrowseHistory::getCreated_at);
        // 执行查询
        List<BrowseHistory> allHistory = browseHistoryMapper.selectWithTimeMapping(wrapper);
        // 合并相同内容的记录
        List<BrowseHistory> mergedHistory = mergeHistory(allHistory, timeRange);
        return PageInfo.of ( mergedHistory);
    }
    private List<BrowseHistory> mergeHistory(List<BrowseHistory> historyList, TimeRange timeRange) {
        if (historyList == null || historyList.isEmpty()) {
            return historyList;
        }
        // 使用Map来存储合并后的记录，键为contentId和targetType的组合
        Map<String, BrowseHistory> mergedMap = new HashMap<> ();
        for (BrowseHistory history : historyList) {
            String key = history.getTargetId() + ":" + history.getTargetType();
            LocalDateTime createdAt = history.getCreated_at();
            // 检查createdAt是否为null
            if (createdAt == null) {
                continue;
            }
            // 如果在指定时间范围内，只保留最新的一条记录
            if (isWithinTimeRange(history.getCreated_at (), timeRange)) {
                mergedMap.put(key, history);
            } else {
                // 如果不在指定时间范围内，直接添加到结果中
                if (!mergedMap.containsKey(key)) {
                    mergedMap.put(key, history);
                }
            }
        }

        return new ArrayList<> (mergedMap.values());
    }
    private boolean isWithinTimeRange(LocalDateTime createdAt, TimeRange timeRange) {
        if (createdAt == null) {
            return false;
        }
        LocalDateTime now = LocalDateTime.now();
        return switch (timeRange) {
            case TODAY -> createdAt.toLocalDate ().equals ( now.toLocalDate () );
            case YESTERDAY -> createdAt.toLocalDate ().equals ( now.minusDays ( 1 ).toLocalDate () );
            case THIS_WEEK -> now.minusDays ( 7 ).isBefore ( createdAt );
            case THIS_MONTH -> now.minusMonths ( 1 ).isBefore ( createdAt );
            case THREE_MONTHS -> now.minusMonths ( 3 ).isBefore ( createdAt );
            case EARLIER -> createdAt.isBefore ( now.minusMonths ( 3 ) );
            default -> false;
        };
    }
    // 时间范围枚举
    public enum TimeRange {
        TODAY, YESTERDAY, THIS_WEEK, THIS_MONTH, THREE_MONTHS, EARLIER
    }
}
